package ru.bytedog.oiot.counter.bot.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import ru.bytedog.oiot.counter.bot.entity.BotUser;
import ru.bytedog.oiot.counter.bot.exception.ServiceException;
import ru.bytedog.oiot.counter.bot.service.dashboard.UserOtpService;

@Slf4j
public class OtpAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {

    private final UserDetailsService userDetailsService;
    private final UserOtpService otpService;

    public OtpAuthenticationProvider(UserDetailsService userDetailsService, UserOtpService otpService) {
        this.userDetailsService = userDetailsService;
        this.otpService = otpService;
    }

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        String presentedPassword = authentication.getCredentials().toString();
        BotUser user = (BotUser) userDetails;
        try {
            otpService.validateCode(presentedPassword, user);
        } catch (ServiceException e) {
            log.error("Ошибка авторизации пользователя {}", user.getUsername(), e);
            throw new BadCredentialsException(e.getMessage());
        }
        log.info("Пользователь {} успешно авторизован", user.getUsername());
    }

    @Override
    protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        return userDetailsService.loadUserByUsername(username);
    }
}
